<?php
class lib_company_new extends lib_base{
	public $table_name = "qc_company_new";
    public $pk = "id";

    public function getList($cond){
        
        $this->orderStatus = array('1'=>'新订单','2'=>'已派单','3'=>'已接单','4'=>'维修中','5'=>'已完成','6'=>'已评价','7'=>'已结算','99'=>'已取消');

        $result = $this->get_loaddata($cond,'id desc','*',5);
        if($result){
            $lists = $result['list'];

            $this->areas = D('company_area')->ids($lists,'area_id');
            
            $this->cates = D('company_cate')->ids($lists,'cate_id');
            $this->zones = D('company_zone')->ids($lists,'zone_id');
			$this->devices = D('company_device')->ids($lists,'device_id');
			$this->admins = D('company_admin')->ids($lists,'admin_id');
			$this->shifus = D('company_admin')->ids($lists,'shifu_id');

            $this->shops = D('company_shop')->ids($lists,'shop_id');
            
            foreach ($lists as $val) {
                
                if($val['photo']){
                    $photos_arr = explode(',', $val['photo']);
                    foreach($photos_arr as $v){
                        // $v2 = $this->oos_host.$v;
                        // $val['photos'][] = $v;
                        $val['photos'][] = D('upload_file')->get_image_url($v);
                        // $val['thumbs'][] = $v2."_thumb.jpg";
                    }
                    $val['img'] = $val['photos'][0];
                }
                $val['area_name'] = $this->areas[$val['area_id']]['name'];
                $val['cate_name'] = $this->cates[$val['cate_id']]['name'];
                $val['admin_name'] = $this->admins[$val['admin_id']]['realname'];
                $val['shifu_name'] = $this->shifus[$val['shifu_id']]['realname'];
                $val['status_name'] = $this->orderStatus[$val['order_status']];

                $val['shop'] = $this->shops[$val['shop_id']];
                // $val['addtime'] = time_tran($val['add_time']);
                // if($val['up_time']){
                //     $val['addtime'] = time_tran($val['up_time']);
                // }
                // if($val['is_top']){
                //     // $val['goods'] = '11111111';
                // }
                // // //点赞
                // $val['logusers'] = D('house_esf_log')->get_logs($val['id']);
                // dump($val);exit;
                $list[] = $val;
            }
            
            
            $data['list'] = $list;
            $data['page'] = $result['showPage']['total_page'] ?? 1;

            return $data;
        }else{
            return false;
        }
        
    }

    // ajax
    public function get_child($data){
        // dump($data);exit;
        $this->obj = D("company_{$data['type']}");
        $cond = "status=1 and parent_id={$data['id']}";
        if($type_ids){
            $cond .= " and id IN ({$data['type_ids']})";
        }
        $res['list'] = $this->obj->findAll(array($cond),'sort asc,id asc');
        $res['info'] = $this->obj->get_info($data['id']);
        return $res;

    }

    public function get_detail($order_id){
        
        $this->order_logObj = D('company_order_log');
    	$info = $this->get_info($order_id);
    	if($info){
           
            $info['area'] = D('company_area')->get_info($info['area_id']);
            $info['parea'] = D('company_area')->get_pinfo($info['area_id']);

			$info['cate'] = D('company_cate')->get_info($info['cate_id']);
            $info['pcate'] = D('company_cate')->get_pinfo($info['cate_id']);

			$info['zone'] = D('company_zone')->get_info($info['zone_id']);
            $info['pzone'] = D('company_zone')->get_pinfo($info['zone_id']);

			$info['admin'] = D('company_admin')->get_info($info['admin_id']);
			$info['shifu'] = D('company_admin')->get_info($info['shifu_id']);

            $info['shop'] = D('company_shop')->get_info($info['shop_id']);
			
			if($info['device_id']){
				$info['device']= D('company_device')->get_detail($info['device_id']);
			}

	        if($info['photo']){
                $photos_arr = explode(',', $info['photo']);
                foreach($photos_arr as $v){
                    $info['photos'][$v] = D('upload_file')->get_image_url($v);
                }
			}

			$cond = "status=1 and order_id={$info['id']}";
			$logs = D('company_order_log')->get_list($cond);
            
			if($logs){
				foreach ($logs as $key => $val) {
					if($val['intro']){
						$val['intro'] = unserialize($val['intro']);
						if($val['intro']['photo']){
                            $photos_arr = explode(',', $val['intro']['photo']);
                            foreach($photos_arr as $v){
                                $val['intro']['photos'][] = D('upload_file')->get_image_url($v);
                            }
						}
						
					}
					$list[] = $val;
				}
				
				$info['logs'] = $list;
				$info['logs_maxid'] = max(array_keys($list));
			}
			
    	}
    	return $info;

    }

    public function admin_act($doids,$status)
    {
        return $this->update(array("{$this->pk} IN ({$doids})"),array('order_status'=>$status));
    }


    public function order_act($order_id,$data){

        $order = D('company_order')->get_info($order_id);
        if($order){
            $arrBase['shifu_id'] = $data['shifu_id'];
            $arrBase['order_status'] = $data['order_status'];
            $arrBase['up_time'] = date('Y-m-d H:i:s');

            if($data['order_status']==5){
                $arrBase['cl_info'] = $data['cl_info'];
                $arrBase['cl_money1'] = $data['cl_money1'];
                $arrBase['cl_money2'] = $data['cl_money2'];
            }
            if($data['order_status']==6){
                $arrBase['pj_stat1'] = $data['pj_stat1'];
                $arrBase['pj_stat2'] = $data['pj_stat2'];
                $arrBase['pj_info'] = $data['pj_info'];
            }
            
            return $this->edit($order_id,$arrBase);
        }
        
    }

    public function pingjia($order_id,$data){
        $data['msg'] = '评价了订单';
        if($data['intro']) $data['intro'] = $data['intro'];

        $order = D('company_order')->get_info($order_id);
        if($order){
            $arrBase = array(
                'star_wx' =>$data['star_wx'],
                'star_info' =>$data['star_info'],
                'shifu_id' =>$data['shifu_id'],
                'order_status' =>$data['order_status'],
                'status' =>1,
                'up_time'=>date('Y-m-d H:i:s'),
            );
            return $this->edit($order_id,$arrBase);
        }
        
    }

    /**
     * 订单导出
     * @param $dataType
     * @param $query
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function exportList($cond,$data)
    {
        // 表格标题
        $tileArray = ['订单号', '区域', '分类', '地点', '位置', '标题', '设备', '报修员',
        '维修师傅', '报修时间', '完成时间', '订单状态', '备注', '评价星际', '评价内容'];
        // 表格内容
        $dataArray = [];
        
        $query = $this->setWhere($cond,$data);
        // 获取订单列表
        $list = $this->findAll(array($query));
        if($list){
            $this->areas = D('company_area')->ids($list,'area_id');
            $this->cates = D('company_cate')->ids($list,'cate_id');
            $this->zones = D('company_zone')->ids($list,'zone_id');
            $this->admins = D('company_user')->ids($list,'admin_id');
            $this->shifus = D('company_user')->ids($list,'shifu_id');
            $this->devices = D('company_device')->ids($list,'device_id');

            $this->orderStatus = array('1'=>'新报修','2'=>'已派单','3'=>'已接单','4'=>'维修中','5'=>'已完成','6'=>'已评价','99'=>'已取消');
        
            foreach ($list as $order) {
                $dataArray[] = [
                    '订单号' => $this->filterValue($order['id']),
                    '区域' => $this->areas[$order['area_id']]['name'],
                    '分类' => $this->cates[$order['cate_id']]['name'],
                    '地点' => $this->zones[$order['zone_id']]['name'],
                    '位置' => $this->filterValue($order['local']),
                    '标题' => $this->filterValue($order['title']),
                    '设备' => $this->devices[$order['device_id']]['name'],
                    '报修员' => $this->admins[$order['admin_id']]['realname'],
                    '维修师傅' => $this->shifus[$order['shifu_id']]['realname'],
                    '报修时间' => $order['add_time'],
                    '完成时间' => $order['up_time'],
                    '订单状态' => $this->orderStatus[$order['order_status']],
                    '备注' => $this->filterValue($order['intro']),
                    '评价星际' => $this->filterValue($order['star_wx']),
                    '评价内容' => $this->filterValue($order['star_info']),
                    // '是否已评价' => $this->filterValue($order['is_comment'] ? '是' : '否'),
                ];
            }
           
        }

         // 导出csv文件
         $filename = 'order-' . date('YmdHis');
         export_excel($filename . '.csv', $tileArray, $dataArray);
    }

    /**
     * 表格值过滤
     * @param $value
     * @return string
     */
    private function filterValue($value)
    {
        return "\t" . $value . "\t";
    }

    private function setWhere($cond,$query)
    {
        $cond = $cond;
        if (isset($query['keyword']) && !empty($query['keyword'])) {
            $cond.=" and (title like '%".$query['keyword']."%') ";
        }
        if (isset($query['area_id']) && !empty($query['area_id'])) {
            $cond .=" and area_id='{$query['area_id']}'";
        }
        if (isset($query['cate_id']) && !empty($query['cate_id'])) {
            $cond .=" and cate_id='{$query['cate_id']}'";
        }
        if (isset($query['zone_id']) && !empty($query['zone_id'])) {
            $cond .=" and zone_id='{$query['zone_id']}'";
        }
        if (isset($query['device_id']) && !empty($query['device_id'])) {
            $cond .=" and device_id='{$query['device_id']}'";
        }
        if (isset($query['shifu_id']) && !empty($query['shifu_id'])) {
            $cond .=" and shifu_id='{$query['shifu_id']}'";
        }
        if (isset($query['time_s']) && !empty($query['time_s'])) {
            $cond .=" and add_time>='{$query['time_s']}'";
        }
        if (isset($query['time_e']) && !empty($query['time_e'])) {
            $cond .=" and add_time<='{$query['time_e']}'";
        }
        if (isset($query['time_s2']) && !empty($query['time_s2'])) {
            $cond .=" and up_time>='{$query['time_s2']}'";
        }
        if (isset($query['time_e2']) && !empty($query['time_e2'])) {
            $cond .=" and up_time<='{$query['time_e2']}'";
        }
        if (isset($query['order_status']) && !empty($query['order_status'])) {
            $cond .=" and order_status='{$query['order_status']}'";
        }

        return $cond;
    }


    public function sendsms($order_id,$order_status,$setting)
    {
        
        $this->setting = D('setting')->get_setting();
        if(!$this->setting['sms']['status']){
            return false;
        }

        if(!$setting['sms_status']){
            return false;
        }
        if(!$setting['sms_order'][$order_status]){
            return false;
        }
        $order = $this->findById($order_id);

        // sms_num
        $company =  D('company')->findById($order['company_id']);
        if($company['sms_num']<=0){
            return false;
        }
        //师傅
        if(in_array($order_status, array(2)) && $order['shifu_id']){
            $admin_id = $order['shifu_id'];
        }else{
            $admin_id = $order['admin_id'];
        }
        $admin =  D('company_user')->findById($admin_id);
        // sms_user1
        if(!$setting['sms_user'][$admin['level']]){
            return false;
        }

        // $pcate =  D('company_cate')->findById($order['cate_pid']);
        $cate =  D('company_cate')->findById($order['cate_id']);
        $zone =  D('company_zone')->findById($order['zone_id']);

        $orderStatus = array(
            '1'=>'新报修',
            '2'=>'已派单',
            '3'=>'已接单',
            '4'=>'维修中',
            '5'=>'已完成',
            '6'=>'已评价',
            '7'=>'已结算',
            '99'=>'已取消'
        );

       
        $this->config = $this->setting['sms'];

        $template_code = $this->config['engine']['aliyun']['order_pay']['template_code'];
        $data = array(
            'template_code' => $template_code,
            'tel' => $admin['tel'],
            'zone' => $zone['name'],
            'cate' => $cate['name'],
            'status' => $orderStatus[$order_status],
        );

        $upSms = new SmsAliyun($this->config['engine']['aliyun']);
        $result = $upSms->sendSms($data);
        $result = object_to_array($result);
        // dump($data);
        // dump($result);exit;
        if($result['Code'] =='OK'){
            D('company')->decr(array('id'=>$company['id']), 'sms_num');
            return true;
        }else{
            return $result;
        }

    }

    
}